import static java.lang.Thread.sleep;

/**
 * ReadWriteLock
 */
public class ReadWriteLock {

    private int readCount = 0;
    private boolean isWrite = false;
    private final Object monitor = new Object();

    public void acquireReadLock(){
        synchronized (monitor){
            while (isWrite){
                try {
                    monitor.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            readCount++;
        }
    }

    public void unReadLock(){
        synchronized (monitor){
            if (!isWrite){
                if (--readCount == 0){
                    monitor.notifyAll();
                }
            }
        }
    }

    public void acquireWriteLock(){
        synchronized (monitor){
            while (readCount>0 || isWrite){
                try {
                    monitor.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            isWrite = true;
        }
    }

    public void unWriteLock(){
        synchronized (monitor){
            if (isWrite){
                isWrite = false;
            }
            monitor.notifyAll();
        }
    }

}